<?php
namespace app\web\controller;

use app\model\Record as Record_mod;
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 
use app\model\Order; 
use app\model\Share; 
use app\model\Scan; 

class Record extends Base
{
    public function Record()
    {
global $_G, $_P;
if (strstr($_SERVER['HTTP_HOST'],".y.yixuan.net")!==false){
    return_msg('请不要使用管理网址操作!');
}

$system = $_G['system'];

$_G['page']['title'] = '参团列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
    return_msg('还没有创建活动,请联系管理员');
}
if(empty($theme['softsn'])){
    return_msg('软件未激活,无法使用');
}

if(empty($theme['softsn'])){
    return_msg('软件未激活,无法使用');
}


$config =   Theme::getConfig($themeid);
$id = intval($_P['id']);
$do = 'record';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));
$refundfee = Order::getRealByThemeIdRefund($themeid);
if ($system['softstyle']==5) {
    $tuanzhang = $config['jmbiemingwenzi'];
    $danmai = $config['jmbiemingwenzi2'];
}else{
    $tuanzhang = '团长';
    $danmai = '单买'; 
}
//Record_mod::deleterecord($system,$themeid,325);

if ($op != 'display') {
    if (!empty($system['tiaozhuanurl'])) {
        if (stripos($system['tiaozhuanurl'],'跳转至')!==false) {
            return_msg("此链接已失效，所有活动已".$system['tiaozhuanurl']);
        }else{
            return_msg("此活动已设置跳转至".$system['tiaozhuanurl'] );
        }   
    }
}

if ($op == 'searchlog') {
    $tiaojian = " where 1=1 ";
    $logtype = $_P['logtype'];
    if (!empty($logtype)) {
        $tiaojian .= " and type = '" . $logtype ."'";
    }
    if (!empty($_P['logkeyword'])) {
        $tiaojian .= " and `desc` like '%" . $_P['logkeyword'] ."%'";
    }
    if (!$_G['isSuperAdmin']){
        $tiaojian .= " and type = '修改定单'";
    }

    $pageNumber = max ( 1, intval ( $_P['page'] ) );
    $pageSize = 20;

    $logsql = "SELECT * FROM " . tablename ( t_log ) . $tiaojian . " ORDER BY id desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
    $log = db_select ( $logsql);

    $logsql = "SELECT COUNT(*) FROM " . tablename ( t_log ) . $tiaojian . " ORDER BY id desc ";
    $logtotal = db_fetchcolumn ($logsql);

    $logsql = "SELECT type,count(id) as shuliang FROM " . tablename ( t_log ) . " group by type ORDER BY type asc";
    $loglist = db_select ( $logsql );
    
    $logsql = "SELECT COUNT(*) FROM " . tablename ( t_log ) . " ORDER BY id desc ";
    $alltotal = db_fetchcolumn ($logsql);

    $logpager = pagination ( $logtotal, $pageNumber, $pageSize );
}

if($op == 'searchtuan') {
    $result = Record_mod::searchtuan($themeid);
    return_msg($result, '', 'ajax');
}
if($op == 'searchfans') {
    $txt = trim($_P['txt']);
    $tuanlist = db_select('SELECT * FROM ' . tablename(t_fans) . ' 
            WHERE themeid = :themeid and (nickname like "%' . $txt . '%" or username like "%' . $txt . '%" or mobile like "%' . $txt . '%")', array( ':themeid' => $themeid));
    if (count($tuanlist)==0) {
        $result = array(
            'errcode' => 0, 
            'msg' => '未搜索到粉丝-' . $txt, 
        );
    }elseif (count($tuanlist)==1) {
        $result = array(
            'errcode' => 1, 
            'tuanlist' => $tuanlist, 
            'msg' => '成功', 
        );
    }elseif (count($tuanlist)>1) {
        $result = array(
            'errcode' => 2, 
            'tuanlist' => $tuanlist, 
            'msg' => '多条记录', 
        );
    }
    return_msg($result, '', 'ajax');
}
if($op == 'edit') {
    $uid = intval($_P['uid']);
    if($uid != 0) {
        $fansinfo = db_find('SELECT * FROM ' . tablename(t_fans) . ' 
            WHERE themeid = :themeid AND uid = :uid', array( ':themeid' => $themeid,':uid' => $uid));
    }
    if($id == 0) {
        return_tips('定单信息不存在', $url, 'success');
    }
    $record = db_find('SELECT * FROM ' . tablename(t_record) . ' 
            WHERE themeid = :themeid AND id = :id', array( ':themeid' => $themeid,':id' => $id));
    if ($record['type']==0 ) {
        $record['pid'] = $record['id'];
    }
    if ($system['tuijianren'] == '1'){
        $fanslist = db_select('SELECT uid,openid,nickname,mobile,username FROM ' . tablename(t_fans) . ' 
            WHERE themeid = :themeid and uid = :uid group by uid order by uid asc', array( ':themeid' => $themeid,':uid' => $record['fromuid']));
    }
    if(empty($record)) {
        return_tips('定单信息不存在', $url, 'success');
    }
    $tuanlist = db_select('SELECT * FROM ' . tablename(t_record) . ' 
            WHERE themeid = :themeid AND status <> 0 and type = 0 and id = :id order by mobile asc', array( ':themeid' => $themeid, ':id' => $record['pid']));
    foreach ($tuanlist as $index => $item) {
        $tuanlist[$index]['renshu'] = Record_mod::getAttendDetailNumByPId($item['id'])+1;
    }


    $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
            left join " . tablename ( t_team ) . " as t on w.team = t.id
            left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
            WHERE w.themeid = :themeid
            ORDER BY company,team,uid  ";
    $wlist = db_select($sql, array(":themeid"=>$themeid));
    
    $url = createWebUrl($do,array('op' => 'edit','themeid'=>$themeid,'uid'=>$uid,'id'=>$id));

    if(checksubmit('submit')) {        
        $beizhu = ''; 
        $opuser = $_G['username'];
        $opuser = str_replace('benben', '管理员', $opuser);

        $data = array(
                'username' => trim($_P['username']),
                'mobile' => trim($_P['mobile']),
                'option' => $_P['shoptitle'],
                'address' => $_P['address_ordernew'],
                'datetime' => $_P['date_ordernew'],
            ); 

        if ($system['tuijianren'] == '1'){
            if (!empty($_P['tuijianren'])) {
                $tuijianren = explode(',',$_P['tuijianren']);
                $data['fromuid'] = $tuijianren[0];
                $data['fopenid'] = $tuijianren[1];
                if ($data['fromuid']!=$record['fromuid']) {
                    $beizhu .= date('Y-m-d H:i:s') . ' 推荐人：'. $record['fromuid'] .' 改为 ' .$data['fromuid'] . ' 操作:' . $opuser . '<br>'; 
                }       
            }
        }

        if ($data['username']!=$record['username']) {
            $beizhu .= date('Y-m-d H:i:s'). ' ' . $config['nametext'] . '：'.$record['username'].' 改为 ' . $data['username'] . ' 操作:' . $opuser . '<br>';
        }
        if ($data['mobile']!=$record['mobile']) {
            $beizhu .= date('Y-m-d H:i:s'). ' ' . $config['mobiletext'] . '：'.$record['mobile'].' 改为 ' . $data['mobile'] . ' 操作:' . $opuser . '<br>';
        }
        if ($data['option']!=$record['option']) {
            $beizhu .= date('Y-m-d H:i:s'). ' ' . $config['shops'] . '：'.$record['option'].' 改为 ' . $data['option'] . ' 操作:' . $opuser . '<br>';
        }
        if ($data['address']!=$record['address']) {
            $beizhu .= date('Y-m-d H:i:s'). ' ' . $config['address'] . '：'.$record['address'].' 改为 ' . $data['address'] . ' 操作:' . $opuser . '<br>';
        }
        if ($data['datetime']!=$record['datetime']) {
            $beizhu .= date('Y-m-d H:i:s'). ' ' . $config['datetime'] . '：'.$record['datetime'].' 改为 ' . $data['datetime'] . ' 操作:' . $opuser . '<br>';
        }

            $workerid = $_P['workerid'];
            if ($workerid != $record['workerid'] ){
                $data['workerid'] = $workerid;
                $tempa = Worker::getThemeWorkerNameByUid($record['workerid'],$themeid,$system['ruanjian']);
                $tempb = Worker::getThemeWorkerNameByUid($workerid,$themeid,$system['ruanjian']);
                $beizhu .= date('Y-m-d H:i:s'). ' 所属员工：'. $tempa .' 改为 ' . $tempb . ' 操作:' . $opuser . '<br>';
                //更新日报表
                if ($record['workerid'] == $record['fromuid']) {
                    db_query("UPDATE ".tablename(t_workerreport)." SET recordzx = recordzx +1,fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                    db_query("UPDATE ".tablename(t_workerreport)." SET recordzx = recordzx -1,fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                }else{
                    db_query("UPDATE ".tablename(t_workerreport)." SET record = record +1,fee = fee + " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $workerid,':riqi' => date("Y-m-d",$record['addtime'])));
                    db_query("UPDATE ".tablename(t_workerreport)." SET record = record -1,fee = fee - " . $record['fee'] . " WHERE themeid =:themeid and workerid =:workerid and riqi =:riqi" ,array(":themeid"=>$themeid,':workerid' => $record['workerid'],':riqi' => date("Y-m-d",$record['addtime'])));
                }
                
                Theme::renewworkreport($themeid,$workerid);
                Theme::renewworkreport($themeid,$record['workerid']);
            }

        $tuanid = $_P['tuanid'];
        if ($tuanid != $record['pid'] && $config['maxcountall']>1){
            $data['pid'] = $tuanid;
            $data['type'] = 1;
            $tempa = $record['pid']+10000;
            $tempb = $tuanid+10000;
            if ($record['type']==0){
                $shenfen = $tuanzhang;
            }elseif ($record['type']==1){
                $shenfen = '团员';
            }elseif ($record['type']==8){
                $shenfen = '补余款';
            }elseif ($record['type']==9){
                $shenfen = $danmai;
            }
            $beizhu .= date('Y-m-d H:i:s'). ' 所属团：'. $tempa . $shenfen .' 改为 ' . $tempb . '团员 操作:' . $opuser . '<br>';
        }
        if (!empty($beizhu)) {
            $data['beizhu'] = $record['beizhu'] . $beizhu;
            writelogcz($system,$themeid,'修改定单',"订单：" . $record['id'] . " 姓名:" . $record['username'] ." 电话:" . $record['mobile'] . '<br>' . $beizhu) ;
        }
        db_update(t_record, $data, array('id' => $_P['id']));

        //更新团状态
        if ($tuanid != $record['pid'] && $config['maxcountall']>1){
            $count = Record_mod::getAttendDetailNumByPId($record['pid']);

            db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $record['pid']) );
            if ($record['renshu']==1) {
                $neednum = intval($config['maxcountall2'])-1;
            }else{
                $neednum = intval($config['maxcountall'])-1;
            }
            if($count >= $neednum){
                Record_mod::setIsfinish($record['pid']);
            }else{
                Record_mod::setNofinish($record['pid']);
            }
            if ($record['type']==0){
                $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                            WHERE  themeid ='{$themeid}' 
                            and (status > 0 or status = -2) and type = 1 and ord.pid='{$record['pid']}' 
                            ORDER BY ord.addtime asc ";
                $list = db_find ( $sql,$params);
                if (!empty($list)){
                    $beizhu = $list['beizhu'];
                    $beizhu .= date('Y-m-d H:i:s'). ' 因团长【'.$record['username'].'】转走，成为新团长 操作:' . $opuser . '<br>';
                    $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array('id' => $list['id']));
                    $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $record['pid']));
                    $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                    
                }
            }

            $count = Record_mod::getAttendDetailNumByPId($tuanid);

            db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $tuanid) );
            if ($record['renshu']==1) {
                $neednum = intval($config['maxcountall2'])-1;
            }else{
                $neednum = intval($config['maxcountall'])-1;
            }
            if($count >= $neednum){
                Record_mod::setIsfinish($tuanid);
            }else{
                Record_mod::setNofinish($tuanid);
            }
        }

        $data = array(
                'username' => trim($_P['username']),
                'mobile' => trim($_P['mobile']),
            );
        if (!empty($_P['uid'])) {
            db_update(t_record, $data, array('uid' => $_P['uid']));
            db_update(t_order, $data, array('uid' => $_P['uid']));
            $data = array(
                    'username' => trim($_P['username']),
                    'mobile' => trim($_P['mobile']),
                    'chongzhi' => floatval($_P['chongzhi']),
                    'beizhu' => $_P['beizhu'],
                );
            db_update(t_fans, $data, array('uid' => $_P['uid']));
        }
        return_tips('更新成功',$url , 'success');
    }
}
if($op == 'refund') {
    $refundno = getMillisecond();
    //return_msg('暂时关闭,如需退款请联系易宣工作人员');
    if (!empty($theme['jiezhang'])){
        return_msg('此活动已结算,无法退款');
    }
    
    $trade = Order::getPayOrderByRIdZhifude($id);
    if (empty($trade)){
        return_msg('此定单未支付或已退');
    }

    if ($refundfee>=$theme['refundfee']){
        return_msg('可退'.$theme['refundfee'].'单,授权已用完,请联系工作人员授权!');
    }


    $totalpayfee = Order::getRealByThemeIdnew($themeid) + $theme['chongzhi'] - $trade['realfee'];
    if ($totalpayfee<-2){
        return_msg('您的余额不足,无法退款,需先充值再退款');
    }

    $ret = Util::applyrefund($trade,$refundno,$system);
    if ($ret['code']==0 || $ret['message']=="-2:订单已全额退款*OK"){
        Record_mod::deleterecord($system,$themeid,$id);
        $state = db_update(t_order, array('paystate' => -1,'refundtime'=>TIMESTAMP), array('id' => $trade['id']));
        $tuanzhang = Record_mod::getPayedGroupById($id,$themeid);

        $item = Record_mod::getById($id);
        $beizhu = $item['beizhu']. date('Y-m-d H:i:s'). ' 全额退款 操作:' . $opuser . '<br>';
        $state = db_update(t_record, array('status' => -1,'isrefund'=>1,'refundtime'=>TIMESTAMP,'beizhu'=>$beizhu), array('id' => $id));
        $state = db_update(t_record, array('isfinish' => 0), array('pid' => $id));

        $count = Record_mod::getAttendDetailNumByPId($id);
        db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $id) );

        writelogcz($system,$themeid,'全额退款',"客户姓名:" . $item['username']."电话:" . $item['mobile'],$_G['username']);

        if (empty($tuanzhang)){
            return_tips('退款成功！', $url, 'success');
        }else{
            $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                        WHERE  themeid ='{$themeid}' 
                        and (status > 0 or status = -2) and type = 1 and ord.pid='{$id}' 
                        ORDER BY ord.addtime asc ";
            $list = db_find ( $sql,$params);
            if (empty($list)){
                return_tips('退款成功！', $url, 'success');
            }else{
                $state = db_update(t_record, array('type' => 0), array('id' => $list['id']));
                $state = db_update(t_record, array('pid' => $list['id']), array('pid' => $id));
                $state = db_update(t_order, array('ordertype' => 0), array('masterid' => $list['id'],'ordertype' => 1));
                $url = createWebUrl($do,array('op2' => 'scan','id' => $list['id'],'themeid'=>$themeid));
                return_tips('退款成功！'.$list['username'].'成为新团长', $url, 'success');
            }
        }
    }else{
        return_tips($ret['message'], $url, 'info');
    }

}


if($op == 'delete') {
    global $_G;
    $sql = "SELECT * FROM " . tablename (t_record) . " WHERE themeid =:themeid and id = :id";
    $record = db_find($sql, array(":themeid"=>$themeid,":id"=>$id));
    if ($_G['isSuperAdmin'] || $record['status']==-2 || $record['status']==3 || $record['status']==0 ){
        Record_mod::deleterecord($system,$themeid,$id);
        $sql = "SELECT * FROM " . tablename (t_order) . " WHERE themeid =:themeid and masterid = :masterid";
        $order = db_find($sql, array(":themeid"=>$themeid,":masterid"=>$id));
        db_delete(t_order, array('masterid' => $id,'themeid'=>$themeid));
        db_delete(t_record, array('id' => $id,'themeid'=>$themeid));           //加盟取消锁定
        if ($record['status']==0){
        $beizhu = "未支付";
        }elseif ( $record['status']==1){
        $beizhu = "已支付";
        }elseif ( $record['status']==2){
        $beizhu = "已核销";
        }elseif ( $record['status']==-1){
        $beizhu = "已退款";
        }elseif ( $record['status']==-2){
        $beizhu = "虚拟定单";
        }elseif ( $record['status']==3){
        $beizhu = "线下定单";
        }else{
        $beizhu = "其他";
        }


        $beizhu = "订单：" . $record['id'] . " 姓名:" . $record['username'] ." 电话:" . $record['mobile'] ." 金额:" . $record['fee'] . "状态:" . $beizhu . "<br>" ."record:" . json_encode($record). "<br>" ."order:" . json_encode($order);
        writelogcz($system,$themeid,'删除定单',$beizhu) ;
        return_tips('删除成功！', $url, 'success');
    }else{
        return_tips('无权操作', $url, 'error');
    }
}

if($op == 'uptuanzhang') {
    $item = Record_mod::getById($id);
    $beizhu = $item['beizhu']. date('Y-m-d H:i:s'). ' 单买升级为拼团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('type' => 0,'beizhu'=>$beizhu), array( 'id' => $id));
    $url =createWebUrl($do, array('op2' => 'scan','themeid'=>$themeid, 'id' => $id));
    return_tips('单买升级为拼团成功！', $url, 'success');
}
if($op == 'xunifinish') {
    $item = Record_mod::getById($id);
    $beizhu = $item['beizhu']. date('Y-m-d H:i:s'). ' 设置虚拟成团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('xunifinish' =>1,'beizhu'=>$beizhu), array( 'pid' => $id));
    return_tips('虚拟成团设置成功', $url, 'success');
}
if($op == 'unxunifinish') {
    $item = Record_mod::getById($id);
    $beizhu = $item['beizhu']. date('Y-m-d H:i:s'). ' 取消虚拟成团 操作:' . $opuser . '<br>';
    $state = db_update(t_record, array('xunifinish' =>0,'beizhu'=>$beizhu), array( 'pid' => $id));
    return_tips('取消虚拟成团设置成功', $url, 'success');
}



if($op == 'display'){
    $pageNumber = max ( 1, intval ( $_P['page'] ) );
    if ($theme['endtime']<strtotime("-90 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben') {
            return_msg('活动结束超3个月,无法查看');
        }
        $pageSize = 20;
    }elseif ($theme['endtime']<strtotime("-30 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
            return_msg('活动结束超1个月,无法查看');
        }
        $pageSize = 20;
    }else{
        $pageSize = 50;
    }

    if (empty($_P['createtime']['start'])){
        $starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
        $starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
    }else{
        $starttime =  strtotime($_P['createtime']['start']);
    }
    $endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
    

    $condition = " and 1=1 "; 

    $condition.= " and ord.addtime > '{$starttime}' and ord.addtime <= '{$endtime}' ";
    
    
    if($_P['op2'] == 'scan'){
        $condition.= " and (ord.pid = '{$id}' or ord.id = '{$id}') ";
    }
    
    $condition .= " and ord.themeid = '{$themeid}' ";
    
    $workerid = $_P['workerid'];
    if(!empty($workerid)){
        $condition.= " and ord.workerid = '{$workerid}'  ";
    }
    if(!empty($_P['zhijie'])){
        $condition.= " and ord.fromuid = '{$workerid}'  ";
    }
    
    $fromuid = $_P['fromuid'];
    if(!empty($fromuid)){
        $condition.= " and (ord.fromuid = '{$fromuid}' )";
    }
    
    $qrimgid = $_P['qrimgid'];
    if(!empty($qrimgid)){
        $condition.= " and (ord.qrimgid = '{$qrimgid}' )";
    }

    if(!isset($_P['type'])){
        $type = -1;
    }else{
        $type = intval($_P['type']);
    }


    if($type == 10){
        $condition.= " and ord.isfinish = '0' and ord.xunifinish = '0' and ord.status >0 ";
    }elseif($type == 11){
        $condition.= " and (ord.isfinish = '1' or ord.xunifinish = '1') and ord.status >0 ";
    }elseif($type >= 0){
        $condition.= " and ord.type = '{$type}'  ";
    }


    if(!isset($_P['status'])){
        $status = -10;
    }else{
        $status = intval($_P['status']);
    }

    if($status == 21){
        $condition.= " and ord.jiagetype = '{$config['joinname']}'  ";
    }elseif($status == 22){
        $condition.= " and ord.jiagetype = '{$config['joinname2']}'  ";
    }elseif($status == 23){
        $condition.= " and ord.jiagetype = '{$config['joinname3']}'  ";
    }elseif($status == -9){
        $condition.= " and ord.type = 0  ";
    }elseif($status >= -5){
        $condition.= " and ord.status = '{$status}'  ";
    }
    

    if($status == -9){
        $sorttype = ' ORDER BY ord.tuannum desc,ord.addtime desc ';
    }elseif($type > 9){
        $sorttype = ' ORDER BY ord.pid desc, ord.type asc, ord.addtime asc';
    }else{
        $sorttype = ' ORDER BY ord.addtime desc ';
    }

    $keyword = trim($_P['keyword']);
    if(!empty($keyword)){
        if (intval($keyword)>10000 && intval($keyword)<30000) {
            $tempa = intval($keyword)-10000;
            $condition.= " and (ord.pid = '". $tempa . "' or ord.id = '". $tempa. "') ";
        } else {
            $condition.= " and (ord.nickname like '%{$keyword}%' or ord.username like '%{$keyword}%' or ord.mobile like '%{$keyword}%'  or ord.option like '%{$keyword}%' or ord.address like '%{$keyword}%' or ord.datetime like '%{$keyword}%')";
        }
    }

    $sql =  "SELECT COUNT(ord.id) FROM " . tablename ( t_record ) . " as ord
            WHERE  1=1  {$condition} ORDER BY ord.id desc";
    $total = db_fetchcolumn ($sql,$params);
    
    
    if(checksubmit('export_submit', true) || checksubmit('export_submit2', true) || checksubmit('export_submit3', true)|| checksubmit('export_submit4', true) || checksubmit('export_submit5', true) || checksubmit('export_submit6', true)){
        if(checksubmit('export_submit', true)){
            $pageNumber=1;
        }elseif(checksubmit('export_submit2', true)){
            $pageNumber=2;
        }elseif(checksubmit('export_submit3', true)){
            $pageNumber=3;
        }elseif(checksubmit('export_submit4', true)){
            $pageNumber=4;
        }elseif(checksubmit('export_submit5', true)){
            $pageNumber=5;
        }elseif(checksubmit('export_submit6', true)){
            $pageNumber=6;
        }
        if ($theme['endtime']<strtotime("-90 day")) {
            if ($_G['username']!=='benben') {
                return_msg('活动结束超3个月,无法导出');
            }
        }elseif ($theme['endtime']<strtotime("-30 day")) {
            if ($_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
                return_msg('活动结束超1个月,无法导出');
            }
        }
        $header = array();
        $header['id'] = '定单号';
        if (!empty($system['wxapp'])){
            $header['uniacid'] = '来自';
        }
        $header['nickname'] = '微信昵称';
        $header['username'] = '姓名';
        $header['mobile'] = '手机';
        if ($system['jiage']>0) {
            $header['jiagetype'] = $config['duojiagetips'];
        }
        if (!empty($config['address'])) {
            $header['address'] = $config['address'];
        }
        if (!empty($config['shops'])) {
            $header['option'] = $config['shops'];
        }
        if (!empty($config['datetime'])) {
            $header['datetime']= $config['datetime'];
        }
            
        $header['fee'] = '金额';
        $header['nickname2'] = '推荐';
        $header['status'] = '状态';
        if ($system['softstyle']==7 && $system['friend']==1) {
            $header['friendnum'] = $config['friend_name'] . '数';
            $header['friendshiyong'] = '已用';
        }elseif ($system['ruanjian']!==1) {
            $header['tuanid'] = '团号';
            $header['tuannum'] = '团人数';
            $header['type'] = '身份';
            $header['isfinish'] = '拼团状态';
        }
        if($config['isicon'] > 0){
            $header['lightsum'] = '点亮数';
        }
        if ($system['fanpai']==1) {
            $header['fanpaijihui'] = '剩余抽奖次数';
            $header['fanpaichoujiang'] = '已抽';
        }
        if ($system['qrlist']==1) {
            $header['qrimgid'] = '二维码ID';
            $header['qrimg'] = '二维码';
        }
        $header['addtime'] = '时间';
        if ($system['ruanjian']==3) {
            $header['companyname']='公司';
        }
        $header['teamname']='团队';
        $header['teamname']='团队';
        $header['workername']='员工';
        $header['chongzhi']='会员卡余额';
        $header['beizhu']='备注';

        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
        $statustr = array("未支付","已支付","已核销","线下定单","已退款","虚拟定单");
        $luckstr = array("否","是");
        $typestr = array($tuanzhang,"团员","补余款",$danmai);
        $groupstr = array("拼团中","拼团成功","虚拟成团");
        // for ($j = 1; $j <= $pagesize; $j++) {
            $pageNumber = max ( 1, intval ( $pageNumber ) );
            $sorttype = ' ORDER BY ord.id asc ';
            $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                        WHERE  1=1 {$condition} 
                          {$sorttype} LIMIT " . ($pageNumber - 1) * 5000 . ",5000 ";
            $list = db_select($sql, $params);
            $array = array();
            foreach ($list as $index =>$row){
                if(!empty($row['fromuid'])){
                    $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " 
                                WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['fromuid']));
                    $list[$index]['nickname2'] = $fans['nickname'];
                    $list[$index]['avatar2'] = $fans['avatar'];
                }
                $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " 
                            WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
                $list[$index]['beizhu'] = $fans['beizhu'];
                $list[$index]['chongzhi'] = $fans['chongzhi'];
                if(!empty($row['workerid'])){
                    $fans = db_find ( "SELECT * FROM " . tablename ( t_worker ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['workerid']));
                    $list[$index]['workername'] = $fans['username'];
                    if (empty($fans['username'])) {
                        $list[$index]['workername'] = $row['workerid'];
                    }
                }
                if ($system['ruanjian']==0 && $system['softstyle']==5 && !empty($row['address'])) {
                    $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= '" . $row['address']."'");
                    $xianname = $item['areaName'];
                    if (!empty($item)){
                        $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
                        $shiname = $item['areaName'];
                    }
                    if (!empty($item)){
                    $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
                    $shengname = $item['areaName'];
                    }
                    $list[$index]['address'] = $shengname . $shiname .$xianname;
                }

                if(!empty($row['workerid'])){
                    $fans = db_find ( "SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
                        left join " . tablename ( t_team ) . " as t on w.team = t.id
                        left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                        WHERE w.uid = :uid and w.themeid =:themeid
                        ",array(":themeid"=>$themeid,":uid"=>$row['workerid']));
                    $list[$index]['workername'] = $fans['username'];
                    $list[$index]['teamname'] = $fans['teamname'];
                    $list[$index]['companyname'] = $fans['companyname'];
                    if (empty($fans['username'])) {
                        $list[$index]['workername'] = $row['workerid'];
                    }
                }

                if ($row['type']==0){
                    $list[$index]['tuanid'] = $row['id']+10000;
                }elseif ($row['type']==1){
                    $list[$index]['tuanid'] = $row['pid']+10000;
                }elseif ($row['type']==9){
                    $list[$index]['tuanid'] = 0;
                }
                if ($system['wxapp']==$row['uniacid']){
                    $list[$index]['uniacid'] = "小程序";
                }else{
                    $list[$index]['uniacid'] = "H5";
                }

                $list[$index]['nickname']=str_replace('"',"",$list[$index]['nickname']);
                $list[$index]['nickname']=str_replace(',',"",$list[$index]['nickname']);
                $list[$index]['nickname2']=str_replace('"',"",$list[$index]['nickname2']);
                $list[$index]['nickname2']=str_replace(',',"",$list[$index]['nickname2']);
                if (empty($list[$index]['nickname2'])){
                    $list[$index]['nickname2']=$row['fromuid'];
                }
                $list[$index]['username']=str_replace('"',"",$list[$index]['username']);
                $list[$index]['username']=str_replace(',',"",$list[$index]['username']);

                $list[$index]['beizhu']=str_replace('"',"",$list[$index]['beizhu']);
                $list[$index]['beizhu']=str_replace(',',"，",$list[$index]['beizhu']);

                $array[] = $list[$index];
                // $details = Record_mod::getAllDetailListByPidAndStatus($row['id'],$status);
                // foreach ($details as $index2 =>$row2){
                //     $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " 
                               //  WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row2['fromuid']));
                //     $details[$index2]['nickname2'] = $fans['nickname'];
                //     $details[$index2]['avatar2'] = $fans['avatar'];
                //     $array[] = $details[$index2];
                // }
                //$array[] = array();
            }

            if (!empty($array)) {
                // $size = ceil(count($array) / 1000);
                // for ($i = 0; $i < $size; $i++) {
                //  $buffer = array_slice($array, $i * 1000, 1000);
                    foreach ($array as $row) {

                        if($row['addtime'] > 0){
                            $row['addtime']  = date('Y-m-d H:i:s',$row['addtime']);
                        }
                        //虚拟成团
                        if ($row['xunifinish']==1){
                            $row['isfinish'] = 2; 
                        }
                        if($row['status'] > 0){
                            $row['status'] = $statustr[$row['status']];
                            $row['isfinish'] = $groupstr[$row['isfinish']]; 
                        }elseif( $row['status'] == -1){
                            $row['status'] = $statustr[4];
                            $row['isfinish'] = ""; 
                        }elseif( $row['status'] == -2){
                            $row['status'] = $statustr[5];
                            $row['isfinish'] = $groupstr[$row['isfinish']]; 
                        }else{
                            $row['status'] = $statustr[$row['status']];
                            if ($row['status'] == 0) {
                                $row['isfinish'] = ""; 
                            }else{
                                $row['isfinish'] = $groupstr[$row['isfinish']]; 
                            }
                        }

                        if ($system['softstyle']==7 && $system['friend']==1) {
                            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
                            $row['friendnum'] = $fans['friendnum'];
                            $row['friendshiyong'] = $fans['friendshiyong'];
                        }

                        if ($system['fanpai']==1){
                            $pm = array(":themeid"=>$themeid,":openid"=>$row['openid']);
                            $yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
                            WHERE themeid = :themeid and openid = :openid",$pm);
                            $row['fanpaichoujiang'] = $yichou;

                            $jihui = $config['fanpailimit']- $yichou;
                            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
                            $row['fanpaijihui'] =  ($jihui>$fans['jihui']) ? $fans['jihui'] : $jihui ;
                        }

                        if($config['isicon'] > 0){
                                if($config['iconnum2'] <= 0){
                                    $lightsum = Share::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);
                                }else{
                                    $lightsum = Scan::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);;
                                    $lightsum = intval($lightsum/$config['iconnum2']);
                                }
                                if($lightsum >= $config['iconnum']){
                                    $lightsum = $config['iconnum'];
                                }
                                $row['lightsum'] =$lightsum;
                        }

                        if ($row['type']==8){$row['type']=2;}
                        if ($row['type']==9){$row['type']=3;}
                        $row['type'] = $typestr[$row['type']];
                        $row['id'] = $row['id']+9000;
                        unset($info);
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        $user[] = implode("\t ,", $data) . "\t ,";
                        unset($data);
                    }
                    $html .= implode("\n", $user);
                // }
            }
        // } 
 
        $r = writelogcz($system,$themeid,'导出数据',count($list) ."条数据导出",$_G['username']);
        if ($r) {
            header("Content-type:text/csv");
            header("Content-Disposition:attachment; filename=活动数据.csv");
            echo $html;
        }
        exit();
    }
    

    //获得按扭文字
    if ($config['groupprice2']>0) {
        $gruoptips = $config['formtextcenter2'];
        $gruoptips = str_replace("#fee",'',$gruoptips);
        $gruoptips = str_replace("#dan",'',$gruoptips);
        $gruoptips = str_replace("#tuan",'',$gruoptips);
        $gruoptips = str_replace("#br",'',$gruoptips);
        $gruoptips = str_replace("￥",'',$gruoptips);
        $gruoptips2 = $gruoptips ;

        $gruoptips = $config['formtextcenter'];
        $gruoptips = str_replace("#fee",'',$gruoptips);
        $gruoptips = str_replace("#dan",'',$gruoptips);
        $gruoptips = str_replace("#tuan",'',$gruoptips);
        $gruoptips = str_replace("#br",'',$gruoptips);
        $gruoptips = str_replace("￥",'',$gruoptips);

        if (empty($config['formtextcenter'])) {
            $gruoptips = $config['maxcountall']."人团";
        }
        if (empty($config['formtextcenter2'])) {
            $gruoptips2 = $config['maxcountall2']."人团";
        }
    }
        
    $themelist = Theme::getAllTheme();

    //统计数据
    $gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}'  and status > 0 " ));
    $gsum0 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}' and type = 0  and status > 0 " ));
    $gsum1 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}' and type = 1  and status > 0 " ));
    $gsum9 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}' and type = 9 and status > 0 " ));   
    $gsum10 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}'  and status > 0 and isfinish = 0 and xunifinish = 0 " ));
    $gsum11 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
            WHERE themeid ='{$themeid}' and status > 0 and (isfinish = 1 or xunifinish = 1)" ));

    $gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
    $gsum13 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status = 0 " ));
    $gsum14 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status = '-1' " ));
    $gsum15 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status = '3' " ));
    $gsum16 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status = '-2' " ));


    $gsum21 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}' and jiagetype='{$config['joinname']}' and r.status > 0 and r.status!=3" ));
    $gsum22 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}' and jiagetype='{$config['joinname2']}' and r.status > 0 and r.status!=3" ));
    $gsum23 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}' and jiagetype='{$config['joinname3']}' and r.status > 0 and r.status!=3" ));

    //统计表单数据
    if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0){
        $tongjitiaojian ='';
    }else{
        $tongjitiaojian =' and status > 0 ';
    }
    $options = "";
    if (!empty($config['options'])) {
        if (!empty($config['gudingoptions'])) {
            $configoptions = array_merge($config['gudingoptions'],$config['options']);
        }else{
            $configoptions =$config['options'];
        }
        foreach ($configoptions as $key => $value) {
            $tempa = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                WHERE themeid ='{$themeid}' and  `option` like '%" . $value . "%' " . $tongjitiaojian ));
            $url = createWebUrl($do, array('themeid'=>$themeid, 'keyword' => $value));
            $options .="<a href=\"". $url . "\" class=\"btn ";
            if (trim($_P['keyword']) == $value){
                $options .= "btn-primary";
            }else{
                $options .= "btn-default";
            }
            $options .= "\">" . $value . "<span style=\"color: #ff0000\">" . $tempa . "</span></a>";
        }
    }
    $addressoptions="";
    if (!empty($config['addressoptions'])) {
        foreach ($config['addressoptions'] as $key => $value) {
            $tempa = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                WHERE themeid ='{$themeid}' and  `address` like '%" . $value . "%' " . $tongjitiaojian ));
            $url = createWebUrl($do, array('themeid'=>$themeid, 'keyword' => $value));
            $addressoptions .="<a href=\"". $url . "\" class=\"btn ";
            if (trim($_P['keyword']) == $value){
                $addressoptions .= "btn-primary";
            }else{
                $addressoptions .= "btn-default";
            }
            $addressoptions .= "\">" . $value . "<span style=\"color: #ff0000\">" . $tempa . "</span></a>";
        }
    }

    //活动免费或有提交参数均不执行
    if (!($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0) && empty($_P['op2']) && empty($_P['workerid']) && empty($_P['zhijie']) && empty($_P['fromuid']) && empty($_P['qrimgid']) &&  empty($_P['keyword']) && $type==-1 && $status==-10){
    //将显示未支付实际支付的清空
        $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                            WHERE  themeid ='{$themeid}' and ord.status=0
                                  ORDER BY ord.addtime desc ";
        $list = db_select ( $sql,$params);

        $array = array();
        foreach ($list as $index =>$row){
            $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                        WHERE  themeid ='{$themeid}' and ord.status>0 and ord.uid='" .$row['uid']."'";
            $isorder = db_find ( $sql);
            if (!empty($isorder)){
                Order::checkorder($themeid,$config,$system,$row['uid']);
                db_delete(t_order, array('masterid' => $row['id'],'paystate'=>0,'themeid'=>$themeid));
                db_delete(t_record, array('id' => $row['id'],'status'=>0,'themeid'=>$themeid));
            }
        }


        //支付成功,团长为空的赋值
        $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                            WHERE  themeid ='{$themeid}' and pid=0 and type=0 and ord.status>0
                                  ORDER BY id desc ";
        $list = db_select ( $sql,$params);

        $array = array();
        foreach ($list as $index =>$row){
            Record_mod::update($row['id'],array('pid'=>$row['id']));
        }
        // echo "执行";
    }


    //员工列表
    $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
            left join " . tablename ( t_team ) . " as t on w.team = t.id
            left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
            WHERE w.themeid = :themeid
            ORDER BY company,team,uid  ";
    $wlist = db_select($sql, array(":themeid"=>$themeid));
    

    $sql = "SELECT ord.* FROM " . tablename ( t_record ) . " as ord
                        WHERE  1=1  {$condition} 
                              {$sorttype}  LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;

    $list = db_select ( $sql,$params);

    foreach ($list as $index =>$row){
        $list[$index]['tynum'] = 0;
        // if($row['type']==0){
        //  $sql =  "SELECT COUNT(ord.id) FROM " . tablename ( t_record ) . " as ord WHERE  ord.pid = '{$row['id']}'";
        //  $dtotal = db_fetchcolumn ($sql);
        //  $list[$index]['tynum'] = $dtotal;
        // }else{
  //           $list[$index]['precord'] = Record_mod::getById($row['pid']);
  //       }

        if ($system['softstyle']==7 && $system['friend']==1) {
            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
            $list[$index]['friendnum'] = $fans['friendnum'];
            $list[$index]['friendshiyong'] = $fans['friendshiyong'];
        }

        if(!empty($row['fromuid'])){
            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['fromuid']));
            $list[$index]['nickname2'] = $fans['nickname'];
            $list[$index]['avatar2'] = $fans['avatar'];
            if (empty($list[$index]['nickname2'])){
                $list[$index]['nickname2']=$row['fromuid'];
            }
        }

        if($config['isicon'] > 0){
                if($config['iconnum2'] <= 0){
                    $lightsum = Share::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);
                }else{
                    $lightsum = Scan::getNumByThemeIdAndOpenidAndStatus($themeid,$row['openid'],1);;
                    $lightsum = intval($lightsum/$config['iconnum2']);
                }
                if($lightsum >= $config['iconnum']){
                    $lightsum = $config['iconnum'];
                }
                $list[$index]['lightsum'] =$lightsum;

        }
        if ($system['fanpai']==1){

            $pm = array(":themeid"=>$themeid,":openid"=>$row['openid']);
            $yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
            WHERE themeid = :themeid and openid = :openid",$pm);
            $list[$index]['fanpaichoujiang'] = $yichou;

            $jihui = $config['fanpailimit']- $yichou;
            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
            $list[$index]['fanpaijihui'] =  ($jihui>$fans['jihui']) ? $fans['jihui'] : $jihui ;
        }

        if(!empty($row['workerid'])){
            $fans = db_find ( "SELECT w.username,t.name as teamname,s.name as companyname FROM " . tablename ( t_worker ) . " as w
                left join " . tablename ( t_team ) . " as t on w.team = t.id
                left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
                WHERE w.uid = :uid and w.themeid =:themeid
                ",array(":themeid"=>$themeid,":uid"=>$row['workerid']));
            $list[$index]['workername'] = $fans['username'];
            $list[$index]['teamname'] = $fans['teamname'];
            $list[$index]['companyname'] = $fans['companyname'];
        }


        if ($system['ruanjian']==0 && $system['softstyle']==5 && !empty($row['address'])) {
            $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= '" . $row['address']."'");
            $xianname = $item['areaName'];
            if (!empty($item)){
                $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
                $shiname = $item['areaName'];
            }
            if (!empty($item)){
            $item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
            $shengname = $item['areaName'];
            }
            $list[$index]['address'] = $shengname . $shiname .$xianname;
        }

        
    }
    //exit;
    $pager = pagination ( $total, $pageNumber, $pageSize );
}

if($op == 'newtuan'){
    $item = Record_mod::getById($id);
    // $p = array(":openid"=>$item['openid'],":themeid"=>$themeid);
    // $item2 = db_find ( "SELECT * FROM " . tablename ( t_record ) . " 
    //          WHERE openid = :openid and themeid =:themeid and type = 0 and status != 0",$p);
    // if(!empty($item2)){
    //  return_tips('当前粉丝已经是团长了');
    // }
    if(empty($item['status'])){
        return_tips('该定单未付款');
    }
    $data = array(
            'uniacid'  => $_G['mpid'],
            'themeid'  => $themeid,
            'openid'   => $item['openid'],
            'uid'      => $item['uid'],
            'nickname' => $item['nickname'],
            'avatar'   => $item['avatar'],
            'username' => $item['username'],
            'mobile'   => $item['mobile'],
            'addtime'  => TIMESTAMP,
            'fee'      => $config['joinfee'],
            'address'  => $item['address'],
            'datetime' => $item['datetime'],
            'option'   => $item['option'],
            'status'   => -2,
            'fromuid'  => $item['uid'],
            'fopenid'  => $item['openid'],
            'workerid'  => $item['workerid'],
            'uid_old'  => $item['uid_old'],
            'openid_old'  => $item['openid_old'],
            'fromuid_old'  => $item['uid_old'],
            'fopenid_old'  => $item['openid_old'],
            'workerid_old'  => $item['workerid_old'],
            'pid'      => 0,
            'type'     => 0,
            'uncode'   => $themeid.'-'.TIMESTAMP.rand(1000,1000000)
    );
    $r = $insertid = db_insert(t_record,$data);
    return_tips('开新团成功！', $url, 'success');
}


//补发多个
if($op == 'refreshall') {
    if (!$_G['isSuperAdmin']){
        return_msg('无权操作');
    }
    $page = max ( 1, intval ( $_P['page'] ) );
    $pagesize = 30;

    $total = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
    echo "正在更新第" . $page . "页/共" .ceil($total / $pagesize) . "页 " . $total . "个支付<br>";


    $sql = "SELECT * FROM " . tablename ( t_record ) . " as r
         WHERE  r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3  LIMIT " . ($page - 1) * $pagesize . ',' . $pagesize;
    $list = db_select ( $sql);
    foreach ($list as $index => $item) {        
        $result = Record_mod::refesh($item['id'],$themeid,$config,$system,$theme);
        echo $result[0] . "<br>";
    }

    if ($page *$pagesize < intval($total )){
        $page = $page+1;
        $url = 'http://'.$_SERVER['HTTP_HOST']."/web/index.php?c=site&a=entry&op=refreshall&do=record&m=".MODULE_NAME. "&page=" . $page ;
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$url';"; 
        echo "</script>";  
        exit;
    }
    exit;
}
//补发单个
if($op == 'refresh') {
    $result = Record_mod::refesh($id,$themeid,$config,$system,$theme);
    if (count($result)>1) {
        $url = createWebUrl('comm',array('keyword' => $result[1],'themeid'=>$themeid));
        return_tips($result[0], $url, 'info');
    }else{
        return_msg($result[0]);
    }
}



$return_clicent = get_defined_vars();
return view('/record' , $return_clicent);
}
}